package com.sts.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.sts.Main;

import javax.swing.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

public class FileChooserTransferHandler extends TransferHandler {

    private final JTextField jTextField;

    public FileChooserTransferHandler(JTextField jTextField) {
        this.jTextField = jTextField;
    }

    @Override
    public boolean canImport(TransferSupport support) {
        boolean isDrop = support.isDrop();
        boolean supported = support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
        return supported && isDrop;
    }

    @Override
    public boolean importData(TransferSupport support) {
        try {
            List<File> list = (List<File>) getFileList(support.getTransferable());
            if (CollectionUtil.isNotEmpty(list)) {
                if (list.size() > 1) {
                    JOptionPane.showMessageDialog(
                            Main.rootFrame,
                            "不支持多个文件",
                            "异常",
                            JOptionPane.ERROR_MESSAGE
                    );
                } else {
                    String absolutePath = list.getFirst().getAbsolutePath();
                    jTextField.setText(absolutePath);
                }
            }
            return !list.isEmpty();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static List<?> getFileList(Transferable transferable) {
        List<?> list;
        try {
            list = (List<?>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
        } catch (UnsupportedFlavorException | IOException ex) {
            list = Collections.emptyList();
        }
        return list;
    }
}
